#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QSerialPort>        //提供访问串口的功能
#include <QSerialPortInfo>    //提供系统中存在的串口的信息

#define SOFT_VERSION "V1.0.0"

MainWindow::MainWindow(
    QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // 设置 左上角的名称
    this->setWindowTitle(tr("cls uart tools ") + SOFT_VERSION);

    // 遍历能用的串口加到 界面串口的下拉框里
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        ui->comboBox->addItem(info.portName());
    }

    /* 创建 open close send 几个信号  连接到 SerilaPort下面的槽函数 */
    connect(this, &MainWindow::open, &serialPort, &BaseSerialport::open);
    connect(this, &MainWindow::close, &serialPort, &BaseSerialport::close);
    connect(this, &MainWindow::send, &serialPort, &BaseSerialport::send);

    /* 将串口放到其他线程 防止主线程崩溃 */
    serialPort.moveToThread(&serialThread);
    serialThread.start();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_UartOn_clicked()
{
    QSerialPort::BaudRate baudRate;
    QSerialPort::StopBits stopBits;
    QSerialPort::DataBits dataBits;
    QSerialPort::Parity dataParity;

    // 波特率
    if (ui->comboBox_2->currentText() == "9600")
    {
        baudRate = QSerialPort::Baud9600;
    }
    else if (ui->comboBox_2->currentText() == "115200")
    {
        baudRate = QSerialPort::Baud115200;
    }

    // 停止位
    if (ui->comboBox_3->currentText() == "1")
    {
        stopBits = QSerialPort::OneStop;
    }
    else if (ui->comboBox_3->currentText() == "1.5")
    {
        stopBits = QSerialPort::OneAndHalfStop;
    }
    else if (ui->comboBox_3->currentText() == "2")
    {
        stopBits = QSerialPort::TwoStop;
    }

    // 数据位
    if (ui->comboBox_4->currentText() == "5")
    {
        dataBits = QSerialPort::Data5;
    }
    else if (ui->comboBox_4->currentText() == "6")
    {
        dataBits = QSerialPort::Data6;
    }
    else if (ui->comboBox_4->currentText() == "7")
    {
        dataBits = QSerialPort::Data7;
    }
    else if (ui->comboBox_4->currentText() == "8")
    {
        dataBits = QSerialPort::Data8;
    }

    // 校验位
    if (ui->comboBox_5->currentText() == "None")
    {
        dataParity = QSerialPort::NoParity;
    }
    else if (ui->comboBox_5->currentText() == "Odd")
    {
        dataParity = QSerialPort::OddParity;
    }
    else if (ui->comboBox_5->currentText() == "Even")
    {
        dataParity = QSerialPort::EvenParity;
    }

    emit open(ui->comboBox->currentText(), baudRate, dataBits, dataParity, stopBits);
}

void MainWindow::on_pushButton_clicked()
{
    QByteArray tx_buf = ui->textEdit->toPlainText().toUtf8();

    emit send(tx_buf);
}

